package sunmi.payment.L3;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;

import com.google.gson.Gson;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import mi.payment.BuildConfig;
import mi.payment.ui.print.helper.TotalSettlementDetail;
import mi.payment.constants.Params;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.MerManagerSettings;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.settings.SystemParamsSettings;
import mi.payment.utils.UIUtils;

/**
 * @author Lee64 on 2017/5/11.
 */

public class L3BroadcastHelper {

    private static final String L3_RESULT_RECEIVER_ACTION = "sunmi.payment.L3.RESULT";

    public static void sendSettlementBroadcast(Context context, TotalSettlementDetail settlementDetail) {
        sendSettlementBroadcast(context, settlementDetail, null);
    }

    /**
     * 发送结算成功广播
     */
    public static void sendSettlementBroadcast(Context context, TotalSettlementDetail settlementDetail, List<PayDetail> list) {
        if (Params.sL3Params == null) return;
        UIUtils.screenMonopoly(-1);
        Intent intent = getResultIntent(null);
        int transNum = Integer.parseInt(settlementDetail.totalNum);
        long totalAmount = Long.parseLong(settlementDetail.totalMoney);
        intent.putExtra("transNum", transNum);
        intent.putExtra("totalAmount", totalAmount);
        intent.putExtra("transDate", settlementDetail.date);
        intent.putExtra("transTime", settlementDetail.time);
        String json = convertPayDetailForStr(list);
        intent.putExtra("settleJson", json);
        context.sendBroadcast(intent);
        Params.sL3Params = null;
    }

    /**
     * 发送余额查询的广播
     */
    public static void sendQueryBalanceBroadcast(Context context, PayDetail payDetail) {
        if (Params.sL3Params == null) return;
        UIUtils.screenMonopoly(-1);
        Intent intent = getResultIntent(null, payDetail);
        intent.putExtra("balance", payDetail.additionalAmount);
        context.sendBroadcast(intent);
        Params.sL3Params = null;
    }

    /**
     * 发送查询本地所有记录的数据
     */
    public static void sendAllTradeListBroadcast(Context context, List<PayDetail> list) {
        if (Params.sL3Params == null) return;
        UIUtils.screenMonopoly(-1);
        Intent intent = getResultIntent(null);
        String json = convertPayDetailForStr(list);
        intent.putExtra("errorCode", 0);
        intent.putExtra("resultCode", 0);
        intent.putExtra("settleJson", json);
        context.sendBroadcast(intent);
        Params.sL3Params = null;
    }

    /**
     * 发送商户信息查询的广播
     */
    public static void sendMerchantInfoBroadcast(Context context) {
        if (Params.sL3Params == null) return;
        UIUtils.screenMonopoly(-1);
        Intent intent = getResultIntent(null);
        String englishName = MerchantSettingsOperation.getInstance().getMerManagerSettings().getMerchantEnglishName();
        intent.putExtra("errorCode", 0);
        intent.putExtra("resultCode", 0);
        intent.putExtra("merchantNameEn", englishName);
        context.sendBroadcast(intent);
        Params.sL3Params = null;
    }

    public static void sendResultBroadcast(Context context, boolean isSuccess, PayDetail payDetail) {
        sendResultBroadcast(context, isSuccess, L3ErrorCode.ERROR_TRADE_FAILED, payDetail);
    }

    /**
     * 发送处理结果广播
     */
    public static void sendResultBroadcast(Context context, boolean isSuccess, L3ErrorCode errorCode, PayDetail payDetail) {
        if (Params.sL3Params == null) return;
        UIUtils.screenMonopoly(-1);
        Intent intent = getResultIntent(errorCode, payDetail);
        if (isSuccess) {
            intent.putExtra("resultCode", 0);
            intent.putExtra("errorCode", 0);
        } else {
            int code = errorCode.getCode();
            String message = L3ErrorCode.getMessage(errorCode);
            intent.putExtra("resultCode", -1);
            intent.putExtra("errorCode", code);
            intent.putExtra("errorMsg", message);
        }
        context.sendBroadcast(intent);
        Params.sL3Params = null;
    }

    /**
     * 发送成功结果广播
     */
    public static void sendSuccessBroadcast(Context context) {
        sendFailedBroadcast(context, null);
    }

    public static void sendFailedBroadcast(Context context, L3ErrorCode errorCode) {
        sendFailedBroadcast(context, errorCode, null);
    }

    /**
     * 发送失败结果广播
     */
    public static void sendFailedBroadcast(Context context, L3ErrorCode errorCode, String msg) {
        if (Params.sL3Params == null) return;
        UIUtils.screenMonopoly(-1);
        Intent intent = getResultIntent(errorCode);
        if (msg != null && msg.length() > 0) {
            intent.putExtra("errorMsg", msg);
        }
        context.sendBroadcast(intent);
        Params.sL3Params = null;
    }

    private static Intent getResultIntent(L3ErrorCode errorCode) {
        return getResultIntent(errorCode, null);
    }

    /**
     * 获取返回的Intent
     */
    private static Intent getResultIntent(L3ErrorCode errorCode, PayDetail payDetail) {
        L3Params params = Params.sL3Params;
        MerManagerSettings mms = MerchantSettingsOperation.getInstance().getMerManagerSettings();
        SystemParamsSettings sps = SystemParamsOperation.getInstance().getSystemParamsSettings();
        String terminalNum = mms.getTerminalNum();
        String merchantNum = mms.getMerchantNum();
        String merchantName = mms.getMerchantName();
        String date = getDate();
        String time = getTime();
        String uId = Params.userInfo.getUId();
        String batchNumStart = sps.getBatchNumStart();

        switch (BuildConfig.FLAVOR) {
            case "lePos":
                merchantNum = mms.getTerminalParamVersion();
                merchantNum = TextUtils.isEmpty(merchantNum) ? mms.getMerchantNum() : merchantNum;
                merchantNum = TextUtils.isEmpty(merchantNum) ? "000000000000018" : merchantNum;
                break;
        }

        Intent intent = new Intent(L3_RESULT_RECEIVER_ACTION);
        intent.setPackage(params.appId);
        intent.putExtra("transType", params.transType);         // 请求类型
        intent.putExtra("model", Build.MODEL);                  // 机型
        intent.putExtra("version", BuildConfig.VERSION_NAME);   // 版本
        intent.putExtra("packageName", BuildConfig.APPLICATION_ID); // 包名
        intent.putExtra("terminalId", terminalNum);             // 终端号
        intent.putExtra("merchantId", merchantNum);             // 商户号
        intent.putExtra("merchantName", merchantName);          // 商户名称
        intent.putExtra("transDate", date);                     // 交易日期
        intent.putExtra("transTime", time);                     // 交易时间
        intent.putExtra("operatorId", uId);                     // 操作员号
        intent.putExtra("batchNo", batchNumStart);              // 批次号
        intent.putExtra("transId", params.transId);             // 交易订单号
        intent.putExtra("amount", params.amount);
        intent.putExtra("paymentType", params.paymentType);

        if (errorCode == null) {
            intent.putExtra("resultCode", 0);
            intent.putExtra("errorCode", 0);
        } else if (payDetail == null) {
            int code = errorCode.getCode();
            String message = L3ErrorCode.getMessage(errorCode);
            intent.putExtra("resultCode", -1);
            intent.putExtra("errorCode", code);
            intent.putExtra("errorMsg", message);
        }

        if (payDetail == null) return intent;
        intent.putExtra("amount", payDetail.amount);
        intent.putExtra("cardNo", payDetail.CardNo);
        intent.putExtra("authNo", payDetail.authNo);
        intent.putExtra("voucherNo", payDetail.voucherNo);
        intent.putExtra("referenceNo", payDetail.referNo);
        intent.putExtra("qrOrderNo", payDetail.thirdTransNum);
        // 如果payDetail不为空，则把用户自定义订单号返回回去。
        String customOrderNo = payDetail.getCustomOrderNo();
        if (customOrderNo != null && customOrderNo.length() > 0) {
            intent.putExtra("transId", customOrderNo);
        }
        if (payDetail.cardType == 1) {
            intent.putExtra("cardType", "MAG");
        } else if (payDetail.cardType == 2) {
            intent.putExtra("cardType", "IC");
        } else if (payDetail.cardType == 4) {
            intent.putExtra("cardType", "NFC");
        }
        intent.putExtra("acquire", payDetail.acquiringBankCode);
        intent.putExtra("issue", payDetail.issuingBankCode);
        intent.putExtra("transDate", payDetail.TradeDate);
        intent.putExtra("transTime", payDetail.TradeTime);
        intent.putExtra("accountType", payDetail.accountType);                  // 账户类型
        intent.putExtra("answerCode", payDetail.tradeAnswerCode);
        intent.putExtra("transactionType", payDetail.transactionType);          // 1:消费 2：消费撤销 3：退货 4.预授权 5.预授权撤销 6.预授权完成 7.预授权完成撤销
        intent.putExtra("transactionPlatform", payDetail.transPlatform);        // 支持的交易平台: 0：银行卡 1：支付宝 2:微信 3:口碑 4:银联钱包
        intent.putExtra("qrCodeScanModel", payDetail.qrCodeScanModel);          // 1.主扫 2.被扫
        intent.putExtra("qrCodeTransactionState", payDetail.QRCodeTransState);  // 扫码支付状态 1：成功；-1：失败 2：支付中

        return intent;
    }

    private static String convertPayDetailForStr(List<PayDetail> tradeList) {
        if (tradeList == null || tradeList.size() == 0) return null;
        List<L3Settlement> list = new ArrayList<>();
        for (PayDetail payDetail : tradeList) {
            L3Settlement settlement = new L3Settlement();
            settlement.amount = payDetail.amount;
            settlement.cardNo = payDetail.CardNo;
            if (payDetail.getCardType() == 1) {
                settlement.cardType = "MAG";
            } else if (payDetail.getCardType() == 2) {
                settlement.cardType = "IC";
            } else if (payDetail.getCardType() == 4) {
                settlement.cardType = "NFC";
            }
            settlement.transId = payDetail.customOrderNo;
            settlement.authNo = payDetail.authNo;
            settlement.batchNo = payDetail.BathNo;
            settlement.voucherNo = payDetail.voucherNo;
            settlement.referenceNo = payDetail.referNo;
            settlement.qrOrderNo = payDetail.thirdTransNum;
            settlement.answerCode = payDetail.tradeAnswerCode;
            settlement.accountType = payDetail.accountType;
            settlement.qrCodeScanModel = payDetail.qrCodeScanModel;
            settlement.transactionType = payDetail.transactionType;
            settlement.transactionPlatform = payDetail.transPlatform;
            settlement.qrCodeTransactionState = payDetail.QRCodeTransState;
            settlement.acquire = payDetail.acquiringBankCode;
            settlement.issue = payDetail.issuingBankCode;
            settlement.tradeTime = payDetail.TradeTime;
            settlement.tradeDate = payDetail.TradeDate;
            list.add(settlement);
        }
        Gson gson = new Gson();
        return gson.toJson(list);
    }

    private static String getDate() {
        SimpleDateFormat format = new SimpleDateFormat("MMdd");
        long timeMillis = System.currentTimeMillis();
        return format.format(timeMillis);
    }

    private static String getTime() {
        SimpleDateFormat format = new SimpleDateFormat("HHmmss");
        long timeMillis = System.currentTimeMillis();
        return format.format(timeMillis);
    }


}
